package com.gitee.minimalismstyle.fresh.common.api.decoder

import com.gitee.minimalismstyle.fresh.common.core.domain.R
import feign.Response
import org.springframework.beans.factory.ObjectFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.http.HttpMessageConverters
import org.springframework.cloud.openfeign.support.SpringDecoder
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type


class RDecoder(messageConverters: ObjectFactory<HttpMessageConverters>) : SpringDecoder(messageConverters) {

    @Value("\${fresh.feign.rdecoder.urls:''}")
    var urls: List<String> = listOf()

    override fun decode(response: Response, type: Type): Any? {

        if(type is ParameterizedType){
            if(type.rawType == R::class.java){
                val url = response.request().url()
                if(urls.any { url.contains(it) }){
                    val data = super.decode(response, type.actualTypeArguments[0])
                    return R.success(data)
                }
            }
        }

        return super.decode(response, type)
    }
}